package models

import (
	"errors"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"time"
)

type Login struct {
	Id       int
	Username string
	Password string
}

type Group struct {
	Id       int
	UserId   int
	GroupId  int
	CreateAt time.Time
}

type Sort struct {
	Id       int
	Username string
	Price    float64
}

var engine *xorm.Engine

func init() {
	var err error
	engine, err = xorm.NewEngine("mysql", "root:root@tcp(127.0.0.1:3306)/table")
	err = engine.Sync2(new(Login), new(Group), new(Sort))
	if err != nil {
		fmt.Println("表格创建失败")
	}
}

func Register(s Sort) error {
	_, err := engine.Insert(&s)
	if err != nil {
		return errors.New("添加失败")
	}
	return nil
}
func GetSort() []Sort {
	var g []Sort
	err := engine.Find(&g)
	if err != nil {
		return []Sort{}
	}
	return g
}

func Ingroup(userid int, groupid int) error {
	var g Group
	_, err := engine.Where("user_id = ? and group_id = ?", userid, groupid).Get(&g)
	if err != nil {
		return err
	}
	return nil
}

func GetUser(groupid int) ([]Group, error) {
	var g []Group
	err := engine.Where("group_id = ?", groupid).Find(&g)
	if err != nil {
		return []Group{}, err
	}
	return g, nil
}

func Admin(username string) (Login, error) {
	var l Login
	_, err := engine.Where("username = ?", username).Get(&l)
	if err != nil {
		return Login{}, errors.New("用户名错误")
	}
	return l, nil
}

func CreateLiveRoom(id, title, image, url, key, e interface{}) error {
	return nil
}
